package cn.hx.security;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 用户信息表(User)表控制层
 *
 * @author makejava
 * @since 2023-12-07 15:02:43
 */
@RestController
public class PublicController {
    public static Map<String,Authentication>tokens=new HashMap<>();


    @Autowired
    AuthenticationManager authenticationManager;


    @GetMapping(value = "login")
    public Map login(String username, String password) {
        // 创建Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);

        // 调用AuthenticationManager的authenticate方法进行认证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (authentication == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        String uuid = UUID.randomUUID().toString();
        //将用户的数据存储
        tokens.put(uuid, authentication);
        return Map.of("token", uuid);
    }

    @GetMapping(value = "userInfo")
    public Map userInfo() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return Map.of("user", principal);
    }

    @GetMapping(value = "logout")
    public Map logout(String token) {
        tokens.remove(token);
        return Map.of("data", "logout");
    }


    @GetMapping(value = "add")
    @PreAuthorize("hasAuthority('security:user:add')")//
    public Map add() {
        return Map.of("data", "add");
    }

    @PreAuthorize("hasAuthority('security:user:delete')")
    @GetMapping(value = "delete")
    public Map admin() {
        return Map.of("data", "delete");
    }

    @GetMapping(value = "test")
    @PreAuthorize("hasAuthority('security:user:test')")
    public Map test() {
        return Map.of("data", "test");
    }


}

